package wechat_bot

import (
	"fmt"
	"time"
	chatgpt3_5 "zy_bot_demo/chatgpt3.5"
)

type GroupTask struct {
	GroupNickName         string `json:"group_nick_name"`
	Message               string `json:"message"`
	SenderInGroupNickName string `json:"sender_in_group_nick_name"`
}

type GroupTaskHandler interface {
	PutGroupTask(task GroupTask)
	HandleGroupTask(task GroupTask)
}

type Worker struct {
	GroupTaskChan chan GroupTask
}

func NewWorker() *Worker {
	return &Worker{
		GroupTaskChan: make(chan GroupTask, 100),
	}
}

var worker *Worker

func (w *Worker) PutGroupTask(task GroupTask) {
	w.GroupTaskChan <- task
}

func (w *Worker) HandleGroupTask(task GroupTask) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(fmt.Sprintf("发生了错误。。。 %v", err))
		}
	}()
	message := task.Message
	resp, err := chatgpt3_5.SendMessage(message)
	if err != nil {
		panic(err)
		println(err)
	}
	task.Message = resp.Choice[0].Message.Content
	go SendGroupMessage(task)
}

func SendGroupMessage(task GroupTask) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(fmt.Sprintf("发生了错误。。。 %v", err))
		}
	}()
	group := FindGroupByGroupNickName(task.GroupNickName)
	if group == nil {
		group.SendText(fmt.Sprintf("@%v \n %v", task.SenderInGroupNickName, task.Message))
	} else {
		fmt.Println("群不存在。。。。。" + task.GroupNickName)
	}
}

func InitWorker() {
	worker = NewWorker()
	go func() {
		for {
			time.Sleep(1 * time.Second)
			select {
			case task, ok := <-worker.GroupTaskChan:
				if !ok {
					println("No messages received... not ok")
				}
				go worker.HandleGroupTask(task)
			default:
				time.Sleep(1 * time.Second)
				println("No messages received...")
			}
		}
	}()
}
